<template>
  <div class="player" v-show="playlist.length > 0">
    <!--1.正常全屏的播发器-->
    <transition name="normal"
                @enter="enter"
                @after-enter="afterEnter"
                @leave="leave"
                @after-leave="afterLeave"
    >
      <div class="normal-player" v-show="fullScreen">
        <div class="background">
          <img :src="currentSong.image" width="100%" height="100%">
        </div>
        <!--顶部-->
        <div class="top">
          <div class="back" @click="back">
            <i class="icon-back"></i>
          </div>
          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="subtitle" v-html="currentSong.singer"></h2>
        </div>
        <!--中间部分 图片 歌曲名称，歌词等-->
        <div class="middle"
             @touchstart.prevent="middleTouchStart"
             @touchmove.prevent="middleTouchMove"
             @touchend="middleTouchEnd"
        >
          <div class="middle-l" ref="middleL">
            <div class="cd-wrapper" ref="cdWrapper">
              <div class="cd" :class="cdCls">
                <img :src="currentSong.image" alt="" class="image">
              </div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{playingLyric}}</div>
            </div>
          </div>
          <!--歌词滚动-->
          <scroll class="middle-r" ref="lyricList" :data="currentLyric && currentLyric.lines">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p
                  class="text"
                  :class="{'current':currentLineNum === index}"
                  ref="lyricLine"
                  v-for="(line,index) in currentLyric.lines"
                  :key="index"
                >
                  {{line.txt}}
                </p>
              </div>
            </div>
          </scroll>
        </div>
        <!--底部 control控制区-->
        <div class="bottom">
          <!--轮播图的点-->
          <div class="dot-wrapper">
            <span class="dot" :class="{'active':currentShow === 'cd'}"></span>
            <span class="dot" :class="{'active':currentShow === 'lyric'}"></span>
          </div>
          <!--播放进度条部分-->
          <div class="progress-wrapper">
            <!--已播放的时间-->
            <span class="time time-l">{{format(currentTime)}}</span>
            <!--播放进度条-->
            <div class="progress-bar-wrapper">
              <progress-bar :percent="percent" @percentChange="onProgressBarChange"></progress-bar>
            </div>
            <!--歌曲总时长-->
            <span class="time time-r">{{format(currentSong.duration)}}</span>
          </div>
          <!--播放控制部分-->
          <div class="operators">
            <!--播放模式-->
            <div class="icon i-left" @click="changeMode">
              <i :class="iconMode"></i>
            </div>
            <!--上一首-->
            <div class="icon i-left" :class="disableCls">
              <i class="icon-prev" @click="prev"></i>
            </div>
            <!--播放-->
            <div class="icon i-center" :class="disableCls">
              <i :class="playIcon" @click="togglePlaying"></i>
            </div>
            <!--下一首-->
            <div class="icon i-right" :class="disableCls">
              <i class="icon-next" @click="next"></i>
            </div>
            <div class="icon i-right">
              <i class="icon" :class="getFavoriteIcon(currentSong)" @click="toggleFavorite(currentSong)"></i>
            </div>
          </div>
        </div>

      </div>
    </transition>
    <!--迷你的播放器-->
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click="open">
        <div class="icon">
          <img :class="cdCls" width="40" height="40" :src="currentSong.image">
        </div>
        <div class="text">
          <h2 class="name" v-html="currentSong.name"></h2>
          <p class="desc" v-html="currentSong.singer"></p>
        </div>
        <div class="control">
          <progress-circle :radius="radius" :percent="percent">
            <!--子元素的点击事件会冒泡到父元素上，stop阻止事件冒泡-->
            <i :class="miniIcon" class="icon-mini" @click.stop="togglePlaying"></i>
          </progress-circle>
        </div>
        <!--控制 播放列表组件显示 playlist-->
        <div class="control" @click.stops="showPlayList">
          <i class="icon-playlist"></i>
        </div>

      </div>
    </transition>
    <!--播放列表组件-->
    <playlist ref="playlist"></playlist>
    <!--播放时通过 H5的audio来播放音乐的-->
    <!--audio api中有定义了。ready,和 error的事件-->
    <audio
      :src="currentSong.url"
      ref="audio" @play="ready"
      @error="error"
      @timeupdate="updateTime"
      @ended="end"
    >

    </audio>

  </div>
</template>

<script type="text/ecmascript-6">
  import {mapGetters, mapMutations,mapActions} from 'vuex'; // 引入vuex控制播放器
  import animations from 'create-keyframe-animation'; // 插件，需要cnpm install
  import {prefixStyle} from "common/js/dom";
  import progressBar from 'base/progress-bar/progress-bar'; // 播放进度条组件
  const transform = prefixStyle('transform');
  import ProgressCircle from 'base/progress-circle/progress-circle'; // 迷你播放器开始/暂停按钮上的播放进度组件
  import {playMode} from 'common/js/config'; // 播放模式
  import {shuffle} from 'common/js/util'; // 引入工具函数进行算法处理
  import Lyric from 'lyric-parser'; // 引入处理歌词字符串的依赖
  import Scroll from 'base/scroll/scroll'; // 引入scroll让歌词滚动

  import Playlist from 'components/playlist/playlist';// 迷你播放器右侧的播放列表组件

  import {playerMixin} from 'common/js/mixin'; // 创建mixin让player和playlist共享使用

  const transitionDuration = prefixStyle('transitionDuration');
  export default {
    name: "player",
    mixins: [playerMixin],
    data() {
      return {
        songReady: false, // 歌曲加载完成，用于控制点击上下一首快速点击
        currentTime: 0,  // 当前的播放时间
        radius: 32,
        currentLyric: null,//歌词
        currentLineNum: 0, // 当前歌词所在的行
        currentShow: 'cd', // 左右滑动的点
        playingLyric: '' // 当前歌词
      }
    },
    computed: {
      ...mapGetters([
        'fullScreen',
        'playlist',
        'currentSong',
        // 'playing',
        // 'currentIndex',
        // 'mode',
        // 'sequenceList' // 顺序播放列表，源列表
      ]),
      // 全屏模式下 ，playIcon 控制显示播放/暂时按钮的样式
      playIcon() {
        return this.playing ? 'icon-pause' : 'icon-play'
      },
      // 迷你播放时，控制播放/暂停的按钮样式
      miniIcon() {
        return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
      },
      // cd旋转的动画
      cdCls() {
        return this.playing ? 'play' : 'play pause'
      },
      // 禁止点击的样式
      disableCls() {
        return this.songReady ? '' : 'disable'
      },
      // 计算 percent歌曲播放的比例 = 已播放的时长/歌曲的总时长 传递给progress-bar进度条组件
      percent() {
        return this.currentTime / this.currentSong.duration;
      },
      // 播放模式图标
      // iconMode() {
      //   return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random'
      // }
    },
    created() {
      this.touch = {}; // 用来关联touchstart touchmove touchend
      // 在移动端播放的问题
      document.querySelector('html').ontouchstart = () => {
        if (this.songReady && window.ONCE_FLAG) {
          window.ONCE_FLAG = false
          this.$refs.audio.play()
        }
      }
    },
    methods: {
      ...mapMutations({
        setFullScreen: 'SET_FULL_SCREEN', // 映射 修改fullScreen的字符串常量
        setPlayingState: 'SET_PLAYING_STATE', // 播放/暂停
        setCurrentIndex: 'SET_CURRENT_INDEX', // 点击上一首下一首时改变 index
        setPlayMode: 'SET_PLAY_MODE', // 修改播放模式的方法
        setPlayList: 'SET_PLAYLIST' // 修改顺序列表list的方法

      }), // vuex的语法糖，引入 mapMutations来修改state状态
      ...mapActions([
        'savePlayHistory' // 记录播放历史记录
      ]),
      // 点击放回按钮时
      back() {
        this.setFullScreen(false); // 当点击返回按钮是，全屏为false,变成迷你播放器了。
      },
      // 点击迷你播放器时变成全屏的
      open() {
        this.setFullScreen(true);
      },
      // 以下是vue的 js 动画钩子
      enter(el, done) {
        const {x, y, scale} = this._getPosAndScale();

        let animation = {
          0: {
            transform: `translate3d(${x}px, ${y}px, 0) scale(${scale})`
          },
          60: {
            transform: `translate3d(0,0,0) scale(1.1)`
          },
          100: {
            transform: `translate3d(0,0,0) scale(1)`
          }
        };
        // 注册动画
        animations.registerAnimation({
          name: 'move',
          animation,
          presets: {
            duration: 400,
            easing: 'linear'
          }
        });
        animations.runAnimation(this.$refs.cdWrapper, 'move', done); // 运行动画
      },
      afterEnter() {
        animations.unregisterAnimation('move');//注销动画
        this.$refs.cdWrapper.style.animation = '';// 清空动画
      },
      leave(el, done) {
        this.$refs.cdWrapper.style.transition = 'all 0.4s';
        const {x, y, scale} = this._getPosAndScale();
        this.$refs.cdWrapper.style[transform] = `translate3d(${x}px, ${y}px, 0) scale(${scale})`;

        this.$refs.cdWrapper.addEventListener('transitionend', done)
      },
      afterLeave() {
        this.$refs.cdWrapper.style.transition = '';
        this.$refs.cdWrapper.style[transform] = '';
      },
      // 定义一个函数，用于计算从全屏播放的图片飞入迷你播放器图片的距离
      _getPosAndScale() {
        const targetWidth = 40;
        const paddingLeft = 40;
        const paddingBottom = 30;
        const paddingTop = 80;
        const width = window.innerWidth * 0.8; // 屏幕的宽度乘以0.8
        const scale = targetWidth / width; // 初始的宽度
        const x = -(window.innerWidth / 2 - paddingLeft);
        const y = window.innerHeight - paddingTop - width / 2 - paddingBottom;

        return {
          x,
          y,
          scale
        }
      },
      // 全屏播放时，播放/暂停按钮
      togglePlaying() {
        // audio中的api play事件控制，当歌曲准备好了的时候，才允许点击
        if (!this.songReady) {
          return
        }
        this.setPlayingState(!this.playing);// 改变播放状态后是不能让音乐停止的，需要监听playing并且设置audio

        // 歌词的设置
        if (this.currentLyric) {
          this.currentLyric.togglePlay();
        }

      },
      // 歌曲播放结束
      end() {
        // 是循环播放模式的时候
        if (this.mode === playMode.loop) {
          this.loop(); // 循环播放
        } else {
          this.next();// 下一首
        }
      },
      loop() {
        this.$refs.audio.currentTime = 0;
        this.$refs.audio.play();
        this.setPlayingState(true);
        if (this.currentLyric) {
          this.currentLyric.seek(0);
        }
      },
      // 全屏（下一首）
      next() {
        if (!this.songReady) {
          return
        }
        // 如果列表只有一首歌曲时点击下一首，就循环这首歌曲
        if (this.playlist.length === 1) {
          this.loop();
          return
        } else {
          // 如果歌曲列表的数量大于1的时候，点击下一首执行以下逻辑
          let index = this.currentIndex + 1;
          // 当前时最后一首歌曲的时候，此时点击下一首应该变成list的第一首歌曲
          if (index === this.playlist.length) {
            index = 0
          }
          this.setCurrentIndex(index); // 调用actions修改currentIndex
          // 点击下一首的时候要改变播放按钮的样式
          if (!this.playing) {
            this.togglePlaying()
          }
        }
        this.songReady = false
      },
      // audio中的事件，当歌曲准备好了的时候
      ready() {
        this.songReady = true;
        this.savePlayHistory(this.currentSong); // 播放的时候记录历史播放记录
      },
      // 当加载audio出现错误的时候
      error() {
        this.songReady = true
      },
      // 全屏（上一首）
      prev() {
        if (!this.songReady) {
          return
        }
        // 如果歌曲的列表只有一首的时候，点击上一首执行循环播放
        if (this.playlist.length === 1) {
          this.loop();
          return
        } else {
        // 如果歌曲列表的数量大于1的时候，点击上一首执行以下逻辑
          let index = this.currentIndex - 1;
          // 当前时第一首歌曲，点击上一首的时候
          if (index === -1) {
            index = this.playlist.length - 1;
          }
          this.setCurrentIndex(index);
          // 点击下一首的时候要改变播放按钮的样式
          if (!this.playing) {
            this.togglePlaying();
          }
        }
        this.songReady = false
      },
      // 获取当前播放的位置时间
      updateTime(e) {
        this.currentTime = e.target.currentTime
      },
      // format函数用于处理timeupdate时间的时间格式的
      format(interval) {
        interval = interval | 0;
        const minute = interval / 60 | 0;
        const second = this._pad(interval % 60);
        return `${minute}: ${second}`
      },
      // 进度条被拖动改变的时候
      onProgressBarChange(percent) {
        const currentTime = this.currentSong.duration * percent;
        this.$refs.audio.currentTime = this.currentSong.duration * percent;

        // 拖动结束后可以播放
        if (!this.playing) {
          this.togglePlaying();
        }
        // 进度条被拖动，歌词也同步
        if (this.currentLyric) {
          this.currentLyric.seek(currentTime * 1000)
        }
      },
      // 点击修改播放模式
      changeMode() {
        // 修改切换播放模式的样式
        const mode = (this.mode + 1) % 3;
        this.setPlayMode(mode); // 修改播放模式的样式
        // 切换模式后，修改播放列表
        let list = null;
        // 随机播放
        if (mode === playMode.random) {
          list = shuffle(this.sequenceList)
        } else {
          // 顺序播放，则不改变源数组
          list = this.sequenceList;
        }
        this.resetCurrentIndex(list); // 保存index
        this.setPlayList(list); // 修改list
      },
      // 保存当前播放的index.
      resetCurrentIndex(list) {
        let index = list.findIndex((item) => {
          return item.id === this.currentSong.id
        });
        this.setCurrentIndex(index);
      },
      getLyric() {
        this.currentSong.getLyric().then((lyric) => {
          // 当前播放的歌词不等于这首歌的歌词时
          if (this.currentSong.lyric !== lyric) {
            return
          }
          this.currentLyric = new Lyric(lyric, this.handleLyric);
          if (this.playing) {
            this.currentLyric.play();
          }
        }).catch(() => {
          // 当找不到歌曲的时候
          this.currentLyric = null;
          this.playingLyric = '';
          this.currentLineNum = 0
        })
      },
      // 当歌词每一行发生改变时的回调
      handleLyric({lineNum, txt}) {
        this.currentLineNum = lineNum;
        // 如果歌词当前的函数大于5 = 歌词的总行数 -5 让高亮当前的歌词保持在中间
        if (lineNum > 5) {
          let lineEl = this.$refs.lyricLine[lineNum - 5];
          this.$refs.lyricList.scrollToElement(lineEl, 1000)
        } else {
          this.$refs.lyricList.scrollTo(0, 0, 1000)
        }
        this.playingLyric = txt // 当前播放的歌词
      },
      // 控制 playlist 播放列表组件的显示隐藏
      showPlayList () {
        this.$refs.playlist.show()
      },
      // 控制在播放页面滑动
      middleTouchStart(e) {
        this.touch.initiated = true; // 标识位
        const touch = e.touches[0];
        this.touch.startX = touch.pageX;
        this.touch.starY = touch.pageY;
      },
      middleTouchMove(e) {
        if (!this.touch.initiated) {
          return
        }
        const touch = e.touches[0];
        const deltaX = touch.pageX - this.touch.startX;
        const deltaY = touch.pageY - this.touch.startY;
        // 如果纵向滚动大于横向的话，认为是纵向滚动，什么都不执行。
        if (Math.abs(deltaY) > Math.abs(deltaX)) {
          return
        }
        const left = this.currentShow === 'cd' ? 0 : -window.innerWidth;
        const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX));
        this.touch.percent = Math.abs(offsetWidth / window.innerWidth);
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`;
        this.$refs.lyricList.$el.style[transitionDuration] = 0;
        this.$refs.middleL.style.opacity = 1 - this.touch.percent;
        this.$refs.middleL.style[transitionDuration] = 0;
      },
      middleTouchEnd() {
        let offsetWidth;
        let opacity;
        if (this.currentShow === 'cd') {
          // 从右向左滑动 滑动超过10%
          if (this.touch.percent > 0.1) {
            offsetWidth = -window.innerWidth;
            opacity = 0;
            this.currentShow = 'lyric';
          } else {
            offsetWidth = 0;
            opacity = 1;
          }
        } else {
          // 从左往右划
          if (this.touch.percent < 0.9) {
            offsetWidth = 0;
            this.currentShow = 'cd';
            opacity = 1;
          } else {
            offsetWidth = -window.innerWidth;
            opacity = 0;
          }
        }
        const time = 300;
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`;
        this.$refs.lyricList.$el.style[transitionDuration] = `${time}ms`;
        this.$refs.middleL.style.opacity = opacity;
        this.$refs.middleL.style[transitionDuration] = `${time}ms`;
      },
      // 处理时间 补0
      _pad(num, n = 2) {
        let len = num.toString().length;
        while (len < n) {
          num = '0' + num;
          len++
        }
        return num;
      }
    },
    // 监听
    watch: {
      // 监听 currentSong 当前歌曲发生变化时执行
      currentSong(newSong, oldSong) {
        // 没有变化的时候
        if (!newSong.id) {
          return
        }
        if (newSong.id === oldSong.id) {
          return
        }
        // 切换歌曲的时候，不会跳动
        if (this.currentLyric) {
          this.currentLyric.stop();
        }
        // $nextTick DOM加载完成后执行
        clearTimeout(this.timer);
       this.timer =  setTimeout(() => {
          this.$refs.audio.play();
          this.getLyric()
        },1000);
      },
      // 监听playing的状态
      playing(newPlaying) {
        const audio = this.$refs.audio;
        // 暂停时点击就播放，
        this.$nextTick(() => {
          newPlaying ? audio.play() : audio.pause();
        });
      }
    },
    components: {
      progressBar,
      ProgressCircle,
      Scroll,
      Playlist
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"
  @import "~common/stylus/mixin"

  .player
    .normal-player
      position: fixed
      left: 0
      right: 0
      top: 0
      bottom: 0
      z-index: 150
      background: $color-background
      .background
        position: absolute
        left: 0
        top: 0
        width: 100%
        height: 100%
        z-index: -1
        opacity: 0.6
        filter: blur(20px)
      .top
        position: relative
        margin-bottom: 25px
        .back
          position absolute
          top: 0
          left: 6px
          z-index: 50
          .icon-back
            display: block
            padding: 9px
            font-size: $font-size-large-x
            color: $color-theme
            transform: rotate(-90deg)
        .title
          width: 70%
          margin: 0 auto
          line-height: 40px
          text-align: center
          no-wrap()
          font-size: $font-size-large
          color: $color-text
        .subtitle
          line-height: 20px
          text-align: center
          font-size: $font-size-medium
          color: $color-text
      .middle
        position: fixed
        width: 100%
        top: 80px
        bottom: 170px
        white-space: nowrap
        font-size: 0
        .middle-l
          display: inline-block
          vertical-align: top
          position: relative
          width: 100%
          height: 0
          padding-top: 80%
          .cd-wrapper
            position: absolute
            left: 10%
            top: 0
            width: 80%
            height: 100%
            .cd
              width: 100%
              height: 100%
              box-sizing: border-box
              border: 10px solid rgba(255, 255, 255, 0.1)
              border-radius: 50%
              &.play
                animation: rotate 20s linear infinite
              &.pause
                animation-play-state: paused
              .image
                position: absolute
                left: 0
                top: 0
                width: 100%
                height: 100%
                border-radius: 50%

          .playing-lyric-wrapper
            width: 80%
            margin: 30px auto 0 auto
            overflow: hidden
            text-align: center
            .playing-lyric
              height: 20px
              line-height: 20px
              font-size: $font-size-medium
              color: $color-text-l
        .middle-r
          display: inline-block
          vertical-align: top
          width: 100%
          height: 100%
          overflow: hidden
          .lyric-wrapper
            width: 80%
            margin: 0 auto
            overflow: hidden
            text-align: center
            .text
              line-height: 32px
              color: $color-text-l
              font-size: $font-size-medium
              &.current
                color: $color-text
      .bottom
        position: absolute
        bottom: 50px
        width: 100%
        .dot-wrapper
          text-align: center
          font-size: 0
          .dot
            display: inline-block
            vertical-align: middle
            margin: 0 4px
            width: 8px
            height: 8px
            border-radius: 50%
            background: $color-text-l
            &.active
              width: 20px
              border-radius: 5px
              background: $color-text-ll
        .progress-wrapper
          display: flex
          align-items: center
          width: 80%
          margin: 0px auto
          padding: 10px 0
          .time
            color: $color-text
            font-size: $font-size-small
            flex: 0 0 30px
            line-height: 30px
            width: 30px
            &.time-l
              text-align: left
            &.time-r
              text-align: right
          .progress-bar-wrapper
            flex: 1
        .operators
          display: flex
          align-items: center
          .icon
            flex: 1
            color: $color-theme
            &.disable
              color: $color-theme-d
            i
              font-size: 30px
          .i-left
            text-align: right
          .i-center
            padding: 0 20px
            text-align: center
            i
              font-size: 40px
          .i-right
            text-align: left
          .icon-favorite
            color: $color-sub-theme
      &.normal-enter-active, &.normal-leave-active
        transition: all 0.4s
        .top, .bottom
          transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32)
      &.normal-enter, &.normal-leave-to
        opacity: 0
        .top
          transform: translate3d(0, -100px, 0)
        .bottom
          transform: translate3d(0, 100px, 0)
    .mini-player
      display: flex
      align-items: center
      position: fixed
      left: 0
      bottom: 0
      z-index: 180
      width: 100%
      height: 60px
      background: $color-highlight-background
      &.mini-enter-active, &.mini-leave-active
        transition: all 0.4s
      &.mini-enter, &.mini-leave-to
        opacity: 0
      .icon
        flex: 0 0 40px
        width: 40px
        padding: 0 10px 0 20px
        img
          border-radius: 50%
          &.play
            animation: rotate 10s linear infinite
          &.pause
            animation-play-state: paused
      .text
        display: flex
        flex-direction: column
        justify-content: center
        flex: 1
        line-height: 20px
        overflow: hidden
        .name
          margin-bottom: 2px
          no-wrap()
          font-size: $font-size-medium
          color: $color-text
        .desc
          no-wrap()
          font-size: $font-size-small
          color: $color-text-d
      .control
        flex: 0 0 30px
        width: 30px
        padding: 0 10px
        .icon-play-mini, .icon-pause-mini, .icon-playlist
          font-size: 30px
          color: $color-theme-d
        .icon-mini
          font-size: 30px
          position: absolute
          left: 0
          top: 0

  @keyframes rotate
    0%
      transform: rotate(0)
    100%
      transform: rotate(360deg)
</style>
